<template>
  <div>
    <h2>工艺路线管理</h2>
    
    <!-- 查询区域 -->
    <div class="search-container">
      <el-select 
        v-model="selectedProductId" 
        placeholder="请选择产品" 
        clearable
        filterable
        style="width: 200px; margin-right: 10px;"
        @change="onProductChange"
      >
        <el-option
          v-for="product in allProducts"
          :key="product.productId"
          :label="`${product.productName} (${product.productId})`"
          :value="product.productId"
        />
      </el-select>
      <el-button type="primary" @click="loadProcessRoutesByProductId" :loading="loading">查询</el-button>
      <el-button @click="resetQuery">重置</el-button>
      <el-button type="primary" @click="showAddRouteDialog" :disabled="!selectedProductId">
        添加工艺路线
      </el-button>
    </div>
    
    <!-- 工艺路线表格 -->
    <el-table 
      :data="processRoutes" 
      style="width: 100%" 
      v-loading="loading"
      border
      stripe
    >
              <el-table-column prop="routeId" label="工艺路线ID" width="150" show-overflow-tooltip sortable />
        <el-table-column prop="productId" label="产品ID" width="150" show-overflow-tooltip sortable />
        <el-table-column prop="routeName" label="工艺路线名称" show-overflow-tooltip sortable />
        <el-table-column prop="productName" label="产品名称" width="180" show-overflow-tooltip sortable />
      <el-table-column label="工序数量" width="100">
        <template #default="scope">
          {{ scope.row.operations ? scope.row.operations.length : 0 }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="editRoute(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteRoute(scope.row)">删除</el-button>
          <el-button size="small" type="info" @click="viewOperations(scope.row)">查看工序</el-button>
          <el-button size="small" type="success" @click="copyRoute(scope.row)">复制</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 工艺路线编辑对话框 -->
    <el-dialog v-model="showDialog" :title="dialogTitle" width="500px">
      <el-form 
        ref="routeFormRef"
        :model="formData" 
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="工艺路线ID" v-if="isEdit">
          <el-input v-model="formData.routeId" disabled />
        </el-form-item>
        <el-form-item label="产品" prop="productId">
          <el-select 
            v-model="formData.productId" 
            placeholder="请选择产品"
            filterable
            style="width: 100%"
            :disabled="isEdit"
          >
            <el-option
              v-for="product in allProducts"
              :key="product.productId"
              :label="`${product.productName} (${product.productId})`"
              :value="product.productId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工艺路线名称" prop="routeName">
          <el-input 
            v-model="formData.routeName" 
            placeholder="请输入工艺路线名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="saveRoute" :loading="saveLoading">
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 工序列表对话框 -->
    <el-dialog v-model="showOperationsDialog" :title="`工序列表 - ${currentRouteName}`" width="80%">
      <div style="margin-bottom: 15px;">
        <el-button type="primary" @click="addOperation" size="small">添加工序</el-button>
        <el-button type="success" @click="goToOperations({routeId: currentRouteId, routeName: currentRouteName})" size="small">
          前往工序管理
        </el-button>
      </div>
      <el-table :data="operations" style="width: 100%" border>
                    <el-table-column prop="operationCode" label="工序编号" width="120" sortable />
            <el-table-column prop="operationName" label="工序名称" width="150" sortable />
            <el-table-column prop="machineTypeName" label="机器类型" width="150" sortable />
            <el-table-column prop="standardTime" label="标准时间(分钟)" width="130" sortable />
            <el-table-column prop="sequenceNo" label="工序顺序" width="100" sortable />
            <el-table-column prop="predecessorOps" label="前置工序" width="120" show-overflow-tooltip sortable />
        <el-table-column label="原料数量" width="100">
          <template #default="scope">
            {{ scope.row.materials ? scope.row.materials.length : 0 }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="editOperation(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteOperation(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="showOperationsDialog = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 复制工艺路线对话框 -->
    <el-dialog v-model="showCopyDialog" title="复制工艺路线" width="500px">
      <el-form 
        ref="copyFormRef"
        :model="copyFormData" 
        :rules="copyFormRules"
        label-width="120px"
      >
        <el-form-item label="源工艺路线">
          <el-input :value="copySourceRoute?.routeName" disabled />
        </el-form-item>
        <el-form-item label="目标产品" prop="targetProductId">
          <el-select 
            v-model="copyFormData.targetProductId" 
            placeholder="请选择目标产品"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="product in allProducts"
              :key="product.productId"
              :label="`${product.productName} (${product.productId})`"
              :value="product.productId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="新工艺路线名称" prop="routeName">
          <el-input 
            v-model="copyFormData.routeName" 
            placeholder="请输入新工艺路线名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCopyDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmCopyRoute" :loading="copyLoading">
          确认复制
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

const API_BASE_URL = 'http://117.72.45.141:8091';

// 定义事件发射器
const emit = defineEmits(['view-operations']);

// 响应式数据
const processRoutes = ref([]);
const operations = ref([]);
const allProducts = ref([]);
const selectedProductId = ref('');
const loading = ref(false);
const saveLoading = ref(false);
const copyLoading = ref(false);

// 对话框状态
const showDialog = ref(false);
const showOperationsDialog = ref(false);
const showCopyDialog = ref(false);
const isEdit = ref(false);
const dialogTitle = ref('添加工艺路线');
const currentRouteName = ref('');
const currentRouteId = ref('');

// 表单引用
const routeFormRef = ref(null);
const copyFormRef = ref(null);

// 表单数据
const formData = reactive({
  routeId: '',
  productId: '',
  routeName: ''
});

const copyFormData = reactive({
  targetProductId: '',
  routeName: ''
});

const copySourceRoute = ref(null);

// 表单验证规则
const formRules = {
  productId: [
    { required: true, message: '请选择产品', trigger: 'change' }
  ],
  routeName: [
    { required: true, message: '请输入工艺路线名称', trigger: 'blur' },
    { min: 1, max: 100, message: '工艺路线名称长度在 1 到 100 个字符', trigger: 'blur' }
  ]
};

const copyFormRules = {
  targetProductId: [
    { required: true, message: '请选择目标产品', trigger: 'change' }
  ],
  routeName: [
    { required: true, message: '请输入新工艺路线名称', trigger: 'blur' },
    { min: 1, max: 100, message: '工艺路线名称长度在 1 到 100 个字符', trigger: 'blur' }
  ]
};

// 加载所有产品
const loadAllProducts = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/api/product/all`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      allProducts.value = response.data.data || [];
    } else {
      ElMessage.error('加载产品列表失败');
    }
  } catch (error) {
    console.error('加载产品列表失败:', error);
    ElMessage.error('加载产品列表失败');
  }
};

// 产品选择变化
const onProductChange = (value) => {
  if (value) {
    loadProcessRoutesByProductId();
  } else {
    processRoutes.value = [];
  }
};

// 通过产品ID加载工艺路线数据
const loadProcessRoutesByProductId = async () => {
  if (!selectedProductId.value) {
    ElMessage.warning('请选择产品');
    return;
  }
  
  loading.value = true;
  try {
    const response = await axios.get(`${API_BASE_URL}/api/process-route/product/${selectedProductId.value}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      processRoutes.value = response.data.data ? [response.data.data] : [];
      if (processRoutes.value.length === 0) {
        ElMessage.info('该产品暂无工艺路线');
      }
    } else {
      ElMessage.warning(response.data.message || '没有获取到工艺路线数据');
      processRoutes.value = [];
    }
  } catch (error) {
    console.error('加载工艺路线失败:', error);
    ElMessage.error('加载工艺路线失败');
    processRoutes.value = [];
  } finally {
    loading.value = false;
  }
};

// 重置查询
const resetQuery = () => {
  selectedProductId.value = '';
  processRoutes.value = [];
};

// 添加工艺路线
const showAddRouteDialog = () => {
  Object.assign(formData, {
    routeId: '',
    productId: selectedProductId.value,
    routeName: ''
  });
  isEdit.value = false;
  dialogTitle.value = '添加工艺路线';
  showDialog.value = true;
  
  if (routeFormRef.value) {
    routeFormRef.value.clearValidate();
  }
};

// 编辑工艺路线
const editRoute = (route) => {
  Object.assign(formData, route);
  isEdit.value = true;
  dialogTitle.value = '编辑工艺路线';
  showDialog.value = true;
  
  if (routeFormRef.value) {
    routeFormRef.value.clearValidate();
  }
};

// 保存工艺路线
const saveRoute = async () => {
  if (!routeFormRef.value) return;
  
  try {
    const valid = await routeFormRef.value.validate();
    if (!valid) return;
  } catch (error) {
    return;
  }
  
  saveLoading.value = true;
  try {
    const url = `${API_BASE_URL}/api/process-route`;
    const method = isEdit.value ? 'put' : 'post';
    
    const response = await axios[method](url, formData, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      ElMessage.success(isEdit.value ? '工艺路线更新成功' : '工艺路线添加成功');
      showDialog.value = false;
      loadProcessRoutesByProductId();
    } else {
      ElMessage.error(response.data.message || '保存失败');
    }
  } catch (error) {
    console.error('保存工艺路线失败:', error);
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message);
    } else {
      ElMessage.error('保存失败，请检查网络连接');
    }
  } finally {
    saveLoading.value = false;
  }
};

// 删除工艺路线
const deleteRoute = async (route) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除工艺路线 "${route.routeName}" 吗？此操作将同时删除所有关联的工序。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    const response = await axios.delete(`${API_BASE_URL}/api/process-route/${route.routeId}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
    ElMessage.success('工艺路线删除成功');
      loadProcessRoutesByProductId();
    } else {
      ElMessage.error(response.data.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
    console.error('删除工艺路线失败:', error);
      ElMessage.error('删除失败，请检查网络连接');
    }
  }
};

// 查看工序
const viewOperations = async (route) => {
  currentRouteName.value = route.routeName;
  currentRouteId.value = route.routeId;
  
  try {
    const response = await axios.get(`${API_BASE_URL}/api/operation/route/${route.routeId}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      operations.value = response.data.data || [];
    } else {
      ElMessage.warning('没有获取到工序数据');
      operations.value = [];
    }
    showOperationsDialog.value = true;
  } catch (error) {
    console.error('加载工序失败:', error);
    ElMessage.error('加载工序失败');
  }
};

// 跳转到工序管理
const goToOperations = (route) => {
  emit('view-operations', route);
};

// 供父组件调用的方法
const setSelectedProduct = (productId) => {
  selectedProductId.value = productId;
  loadProcessRoutesByProductId();
};

// 暴露方法给父组件
defineExpose({
  setSelectedProduct
});

// 复制工艺路线
const copyRoute = (route) => {
  copySourceRoute.value = route;
  Object.assign(copyFormData, {
    targetProductId: '',
    routeName: `${route.routeName}_复制`
  });
  showCopyDialog.value = true;
  
  if (copyFormRef.value) {
    copyFormRef.value.clearValidate();
  }
};

// 确认复制工艺路线
const confirmCopyRoute = async () => {
  if (!copyFormRef.value) return;
  
  try {
    const valid = await copyFormRef.value.validate();
    if (!valid) return;
  } catch (error) {
    return;
  }
  
  copyLoading.value = true;
  try {
    const response = await axios.post(`${API_BASE_URL}/api/process-route/copy`, null, {
      params: {
        sourceRouteId: copySourceRoute.value.routeId,
        targetProductId: copyFormData.targetProductId,
        routeName: copyFormData.routeName
      },
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      ElMessage.success('工艺路线复制成功');
      showCopyDialog.value = false;
      // 如果当前选中的产品是目标产品，刷新列表
      if (selectedProductId.value === copyFormData.targetProductId) {
        loadProcessRoutesByProductId();
      }
    } else {
      ElMessage.error(response.data.message || '复制失败');
    }
  } catch (error) {
    console.error('复制工艺路线失败:', error);
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message);
    } else {
      ElMessage.error('复制失败，请检查网络连接');
    }
  } finally {
    copyLoading.value = false;
  }
};

// 工序管理相关方法（这里简化处理，实际应该跳转到工序管理页面或组件）
const addOperation = () => {
  ElMessage.info('添加工序功能将在工序管理组件中实现');
};

const editOperation = (operation) => {
  ElMessage.info(`编辑工序: ${operation.operationName}`);
};

const deleteOperation = async (operation) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除工序 "${operation.operationName}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    const response = await axios.delete(`${API_BASE_URL}/api/operation/${operation.operationId}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      ElMessage.success('工序删除成功');
      // 重新加载工序列表
      viewOperations({ routeId: currentRouteId.value, routeName: currentRouteName.value });
    } else {
      ElMessage.error(response.data.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除工序失败:', error);
      ElMessage.error('删除失败，请检查网络连接');
    }
  }
};

onMounted(() => {
  loadAllProducts();
});
</script>

<style scoped>
.search-container {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}
</style>